<template>
    <div class="label-tree-wrapper">
        <Block>
            <div class="title-box">
                <div>标签</div>
                <el-icon @click="onCreateEdit('新建标签', { labelTypeNo: activeCategory })"><Plus /></el-icon>
            </div>
            <div class="categorization-box">
                <el-input v-model="filterText" placeholder="标签名称" />
                <el-tree
                    ref="treeRef"
                    :data="treeData"
                    :props="defaultProps"
                    default-expand-all
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    node-key="labelNo"
                    draggable
                    :allow-drop="allowDrop"
                    :allow-drag="allowDrag"
                    @node-drop="handleDrop"
                >
                    <template #default="{ data, node }">
                        <div class="custom-node-box">
                            <div class="custom-node-label">{{ data.labelName }}</div>
                            <div class="custom-node-btn">
                                <el-icon color="#409EFF" v-if="node.level < 5" @click="onCreateEdit('新建标签', data)">
                                    <Plus />
                                </el-icon>
                                <el-icon color="#409EFF" @click="onCreateEdit('修改标签', data)"><Edit /></el-icon>
                                <el-icon color="#F56C6C" @click="onDel(data)"><Delete /></el-icon>
                            </div>
                        </div>
                    </template>
                </el-tree>
            </div>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { Block } from '@great/components';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ref, watch } from 'vue';
import type { AllowDropType, FilterNodeMethodFunction, TreeInstance } from 'element-plus';
import type Node from 'element-plus/es/components/tree/src/model/node';
import { showPopupBox } from '@great/utils';
import CreateEditModal from './CreateEditModal.vue';
import { runLabelService } from '@great/services';

interface Tree {
    [key: string]: any;
}
const props = defineProps<{
    activeCategory?: string;
}>();
const filterText = ref('');
const treeRef = ref<TreeInstance>();
const defaultProps = {
    children: 'childLabel',
    label: 'labelName'
};
const treeData = ref<Tree[]>([]);
// 筛选
watch(filterText, val => {
    treeRef.value!.filter(val);
});
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
    if (!value) return true;
    return data.labelName.includes(value);
};

// 拖拽时判定目标节点能否成为拖动目标位置
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
    if (draggingNode.data.parentLabelNo == dropNode.data.parentLabelNo && type != 'inner') {
        return true;
    } else {
        return false;
    }
};
// 判断节点能否被拖拽
const allowDrag = () => {
    return true;
};
// 拖拽完成回调
const handleDrop = (draggingNode: Node) => {
    let targetSortNo: string[];
    let parentLabelNo = draggingNode.data.parentLabelNo;
    if (parentLabelNo) {
        let target = treeRef.value?.getNode(parentLabelNo);
        targetSortNo = target?.data.childLabel.map(item => item.labelNo);
    } else {
        targetSortNo = treeData.value.map(item => item.labelNo);
    }
    runLabelService.sortLabel({
        parentLabelNo,
        labelTypeNo: props.activeCategory as string,
        labelNos: targetSortNo
    });
};
// 创建/编辑
const onCreateEdit = (type: string, row?: Tree) => {
    showPopupBox(CreateEditModal, {
        type,
        row,
        callBack: getData
    });
};
// 删除
const onDel = (row: { labelName: string; labelNo: string }) => {
    ElMessageBox.confirm(`是否确认删除标签 ${row.labelName} ？`, '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await runLabelService.delLabel(row?.labelNo);
            ElNotification({
                title: '删除成功！',
                type: 'success'
            });
            getData();
        })
        .catch(() => {});
};

const getData = async () => {
    const res = await runLabelService.getLabelTree({ labelTypeNo: props.activeCategory as string });
    treeData.value = res.data;
};
watch(
    () => props.activeCategory,
    val => {
        if (val) {
            getData();
        } else {
            treeData.value = [];
        }
    }
);
</script>
<style scoped lang="scss">
.label-tree-wrapper {
    width: calc(100% - 310px);
    .title-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ddd;
        font-size: 16px;
        font-weight: 600;
        padding-bottom: var(--app-margin);
        margin-bottom: var(--app-margin);
        .el-icon {
            cursor: pointer;
        }
    }
    .categorization-box {
        > .el-input {
            margin-bottom: var(--app-margin);
        }
        .custom-node-box {
            width: 100%;
            height: 100%;
            overflow: hidden;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .custom-node-label {
                line-height: var(--el-tree-node-content-height);
                width: calc(100% - 45px);
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
            .custom-node-btn {
                line-height: 100%;
                display: none;
                .el-icon {
                    cursor: pointer;
                    font-size: 16px;
                    margin-right: 5px;
                }
            }
        }
        .custom-node-box:hover {
            .custom-node-btn {
                display: block;
            }
        }
    }
}
</style>
